//
//  Register_Home_ViewController.m
//  chilemat
//
//  Created by Cristian Gonzalez Figueroa on 05-05-14.
//  Copyright (c) 2014 Chilemat SpA. All rights reserved.
//

#import "Register_Home_iPad_ViewController.h"
#import "dao.h"
#import "Flurry.h"

@interface Register_Home_iPad_ViewController ()

@end

@implementation Register_Home_iPad_ViewController

@synthesize textEmail, textPassword, textRetypePassword;
@synthesize viewContactDetail;
@synthesize json;
@synthesize btnIngresar;

UIActivityIndicatorView *aiViewBtnRegisteriPad;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void) touchesBegan :(NSSet *) touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    
    [super touchesBegan:touches withEvent:event ];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (textField == textEmail) {
        
        [textEmail resignFirstResponder];
        [textPassword becomeFirstResponder];
        
    }else if (textField == textPassword) {
        
        [textPassword resignFirstResponder];
        [textRetypePassword becomeFirstResponder];
        
    }else if (textField == textRetypePassword) {
        
        [self.view endEditing:YES];
    }
    
    return NO;
}

- (void)viewWillAppear:(BOOL)animated {
    
    dao *objDAO = [[dao alloc] init];
    
    //0 = Home App
    //1 = Register
    //2 = Edición del despacho
    
    if ([objDAO obtainRegisterBack] == -1) {
        
        [objDAO deleteRegisterBack];
        [objDAO insertRegisterBack:1];
    }
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.textEmail.delegate = self;
    self.textPassword.delegate = self;
    self.textRetypePassword.delegate = self;
    
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (IBAction)backToLogin:(id)sender {
    
    dao *objDAO = [[dao alloc] init];
    
    //0 = Home App
    //1 = Register
    //2 = Edición del despacho
    
    int intIdRegisterBack = 0;
    
    intIdRegisterBack = [objDAO obtainRegisterBack];
    
    if (intIdRegisterBack == 0) {
        
        [self.navigationController popToRootViewControllerAnimated:YES];
    }else{
        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
    }
    
}

- (IBAction)callNumber:(id)sender {
    
    NSString *strContactPhone;
    
    dao *objDAO = [[dao alloc] init];
    
    strContactPhone = [NSString stringWithFormat:@"tel://%@", [objDAO obtainCallCenterNumber]];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strContactPhone]];
}

- (IBAction)gotoRegister:(id)sender {
    
    //  dao *objDAO = [[dao alloc] init];
    
    //0 = Home App
    //1 = Register
    //2 = Edición del despacho
    
    //  [objDAO deleteRegisterBack];
    //  [objDAO insertRegisterBack:1];
    
    [Flurry setUserID:@"1"];
    
    [self performSegueWithIdentifier:@"segueRegisterData" sender:nil];
}

- (BOOL) validEmail:(NSString*) emailString {
    
    if([emailString length]==0){
        return NO;
    }
    
    NSString *regExPattern = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    
    NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
    NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
    
    //  NSLog(@"%lu", (unsigned long)regExMatches);
    
    if (regExMatches == 0) {
        return NO;
    } else {
        return YES;
    }
}

- (BOOL) validateInputs{
    
    bool blnRetorno = YES;
    bool blnValidarEmail = YES;
    
    if ((textEmail.text.length == 0) && (blnRetorno)) {
        
        blnRetorno = NO;
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"Debe ingresar un Email."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        
        [textEmail becomeFirstResponder];
    }
    
    if (blnRetorno) {
        
        blnValidarEmail = [self validEmail:textEmail.text];
        
        if (!blnValidarEmail) {
            blnRetorno = NO;
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:@"El Email ingresado no es correcto."
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            
            [textEmail becomeFirstResponder];
        }
    }
    
    if ((textPassword.text.length == 0) && (blnRetorno)) {
        
        blnRetorno = NO;
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"Debe ingresar un Password."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        
        [textPassword becomeFirstResponder];
    }
    
    if ((textRetypePassword.text.length == 0) && (blnRetorno)) {
        
        blnRetorno = NO;
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"Debe confirmar su Password."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        
        [textRetypePassword becomeFirstResponder];
    }
    
    if (![textRetypePassword.text isEqualToString:textPassword.text] && (blnRetorno)) { //Si no son iguales alertar
        
        blnRetorno = NO;
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"Las contraseñas deben ser iguales."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        
        [textRetypePassword becomeFirstResponder];
    }
    
    return blnRetorno;
}

-(int) loginUserCLoud:(int) intIdUsuario strEmail:(NSString *) strEmail strPassword:(NSString *) strPassword{
    
    /*
     Parámetros de Entrada:
     Id de usuario
     Email
     Contraseña
     
     IF (Si el correo no existe = UPDATE al usuario y retornar el ID de usuario + ID_Estado = 1)
     
     ELSE IF ( Si el correo ya existe y el password corresponde = UPDATE al usuario y retornar el ID de usuario + ID_Estado = 2. )
     
     ELSE IF (Si el correo ya existe y el password no corresponde = No hacer nada y retornar el ID de usuario = 0 + ID_Estado = 3)
     */
    
    strEmail = [strEmail lowercaseString];
    
    //Create or Product Shopping Cart
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonRegistraUsuario.aspx?strJsonBase=JsonUsuarioUpd&strIdUsuario=%i&strIdSocialLogin=%@&strClaveUsuarioSistema=%@", intIdUsuario, strEmail, strPassword];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    NSURLResponse * response = nil;
    NSError * error = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                          returningResponse:&response
                                                      error:&error];
    if (error == nil)
    {
        //[{"usr":"38", "est":"2" }]
        json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        
        int intIdRetorno = [ [[json objectAtIndex:0] objectForKey:@"est"] intValue];
        int intIdUsuarioExistente = [ [[json objectAtIndex:0] objectForKey:@"usr"] intValue];
        
        if (intIdRetorno == 2) { //Correo y password existen
            
            if (intIdUsuario != intIdUsuarioExistente) {//Significa que el usuario hizo logout y volvió a comprar, se actualiza en Amazon el carro y debe hacerse lo mismo localmente.
                dao *objDAO = [[dao alloc] init];
                [objDAO deleteCurrentIdUser];
                [objDAO insertCurrentIdUser:intIdUsuarioExistente];
                
                //Update al usuario del carro de compras local.
                //- (int ) updateUserShoppingCart:(int) intIdUsuario intIdUsuarioNew:(int) intIdUsuarioNew{
                
                [objDAO updateUserShoppingCart:intIdUsuario intIdUsuarioNew:intIdUsuarioExistente];
            }
            
            return 1;
            
        }else if(intIdRetorno == 1){ //Correo no existe
            
            return 1;
        }
        else{ //Si el correo ya existe y el password no corresponde = No hacer nada
            return 3;
        }
        
        [aiViewBtnRegisteriPad stopAnimating];
        
        return 1;
    }else{
        
        NSLog(@"Error");
        
        [aiViewBtnRegisteriPad stopAnimating];
        return -1;
    }
}

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    
    bool blnRetorno = NO;
    
    blnRetorno = [self validateInputs];
    
    if (blnRetorno) {
        
        if ([identifier isEqualToString:@"segueRegisterData"]){
            
            dao *objDAO = [[dao alloc] init];
            
            //----------------------------------------------------------------
            //Observación: Llamada remota al Cloud para crear el Id usuario
            //----------------------------------------------------------------
            UIActivityIndicatorView *aiViewBtnIngresar;
            
            aiViewBtnIngresar = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            aiViewBtnIngresar.hidesWhenStopped = YES; //I added this just so I could see it
            
            [aiViewBtnIngresar setFrame:CGRectMake(210, 20, 40, 40)];
            
            [self.btnIngresar addSubview:aiViewBtnIngresar];
            
            [aiViewBtnIngresar startAnimating];
            
            //Puede existir un cambio de usuario en el cloud
            int intIdUsuario = [objDAO obtainCurrentIdUser];
            
            int intRetornoCloud = [self loginUserCLoud:intIdUsuario strEmail:textEmail.text strPassword:textPassword.text];
            
            //Puede existir un cambio de usuario en el cloud
            intIdUsuario = [objDAO obtainCurrentIdUser];
            
            [Flurry setUserID:[NSString stringWithFormat:@"%i", intIdUsuario]];
            
            if (intRetornoCloud == 1) { //Login correcto, Update al usuario existiera o no el correo.
                //-----------------------------------------------------
                //Marcamos el login con Correo.
                [objDAO insertUsrLogged:5 idUsuario:intIdUsuario]; //5.- Logeado con correo, 1.- Logeado con Facebook
                
                NSString *strUser, *strPassword, *strSocialLogin, *strEmail;
                
                strUser = @"";
                strPassword = textPassword.text;
                strEmail = textEmail.text;
                
                int intExisteIdUsuario = [objDAO obtainUserSistem:intIdUsuario];
                
                if (intExisteIdUsuario == -1) { //Si no existe lo creo, sino lo actualizo
                    
                    [objDAO insertUserSistem:intIdUsuario strUser:strUser strPassword:strPassword strSocialLoginId:strSocialLogin strEmail:strEmail];
                    
                }else{
                    [objDAO updateUserSistem:intIdUsuario strUser:strUser strPassword:strPassword strSocialLoginId:strSocialLogin strEmail:strEmail];
                    
                }
                //-------------------------------------------------------------------------------------------------------------------------
                //Necesitamos identificar si la sección siguiente viene en modo de ingreso o de edición de información
                [objDAO deleteClientAction];
                [objDAO insertClientAction:@"Ingreso"];
                
                //Variable de Email para utilizar en el registro del sistema
                NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
                // saving an NSString
                [prefs setObject:@"" forKey:@"strEmailCurrentUser"];
                
            }else{ //Retorno = 3
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:@"El email existe en el sistema, pero su contraseña ingresada es incorrecta."
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
                [alert show];
                
                blnRetorno = NO;
            }
        }
        
    }
    
    return blnRetorno;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"segueRegisterData"])
    {
        NSLog(@"Segue !!!!!!!");
        
    }
}


@end
